import WxRequest from './wxrequest/index'
import $cache from './wxCache'

const extConfig = wx.getExtConfigSync();
const service = new WxRequest({
  baseUrl: extConfig.requestDomain
})

service.interceptors.request.use((config) => {
  let token = $cache.get("token")
  config.header = config.header || {}
  config.header['X-APP-ID'] = extConfig.appId;
  config.header['X-WXAPP-TOKEN'] = token;
  config.header['X-VERSION'] = extConfig.versionId;
  config.header['X-BUSINESS-ID'] = extConfig.businessId;
  if (!config.header['content-type']) {
    config.header['content-type'] = 'application/json;charset=utf-8'
  }
  const $app = getApp()
  if ($app && $app.globalData && $app.globalData.GLOBAL_SHOP_ID) {
    config.header['GLOBAL-SHOP-ID'] = $app.globalData.GLOBAL_SHOP_ID
  }
  if ($app && $app.globalData && $app.globalData.GLOBAL_PROMOTER_ID) {
    config.header['GLOBAL-PROMOTER-ID'] = $app.globalData.GLOBAL_PROMOTER_ID
  }
  return config;
})

service.interceptors.response.use((response) => {
  if(response&&response.header&&response.header.date){
    const $app = getApp()
    $app.globalData.serviceDate=response.header.date
  }
  let request = response['__request__']
  if(response.statusCode === 429){
    console.error("请求失败: ", response);
    wx.showToast({ "title": "请求过于频繁" , icon: "none"})
    return Promise.reject(response);
  }else if (response.statusCode !== 200) {
    console.error("请求失败: ", response);
    wx.showToast({ "title": response.data.message , icon: "none",duration:4000})
    return Promise.reject(response);
  }
  const res = response.data
  // 返回头部
  res._header_ = response.header;
  let whileCodeList = [50001, 2, 65001, 50600, 50601, 50002, 61000, 50404, 71002]

  // 仅在体验版输出 console.log ，方便其他开发者查看
  let envVersion = __wxConfig.envVersion  //开发版 develop  体验版 trial  正式版 release
  if(envVersion == 'trial'){
    console.log('请求',request)
    console.log('请求返回值---',res)
  }

  if (res.code === 0) {
    return res
  }if (res.code === 40002 || res.code === 40001) { // token被删除
    if (response['__request__'].header
      && response['__request__'].header['X-WXAPP-TOKEN'] === $cache.get("token")) {
      // 仅当token无效时候, 才清除
      $cache.del("token");
      $cache.del("anonUser");
    }
    // console.error("response.data", response.data)
    // wx.showToast({
    //   title: "" + res.code + ' ' + res.msg,
    //   icon: 'none',
    //   duration: 4000
    // })
    return Promise.reject(response);
  } else if (request.ignoreError) {
    // 忽略错误, 自己处理请求错误
    return res;
  } else if (whileCodeList.indexOf(res.code ) !== -1) {
    return res;
  } else if (res.code === 50602) {//会员未初始化密码
    wx.showModal({
      title: '提示',
      content: res.msg,
      success: (sm) => {
        if (sm.confirm) {
          // todo 优化跳转设置密码
          // $navigateUtils.navigateTo('memberCardModule', 'settingPassword', [{ page: 'app' }, { fai: 1 }])
        }
      }
    })
  } else if (res.code === 62001) {
    let header = {}
    header['X-APP-ID'] = extConfig.appId
    header['X-BUSINESS-ID'] = extConfig.businessId;
    wx.login({ success: (res) => { wx.request({ url: extConfig.requestDomain + '/uaa/wxapp/login_by_code?code=' + res.code, header: header, method: 'POST' }) } })
    return res;
  } else {
    $cache.set("user_info",response.data.data)
    wx.showToast({
      title: res.msg,
      icon: 'none',
      duration: 4000
    })
    return Promise.reject(response);
  }
});
export default service;
